package cn.portx.frame.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.stereotype.Component;

import com.bstek.bdf3.jpa.JpaUtil;
import com.bstek.bdf3.jpa.initiator.JpaUtilAble;
import com.bstek.bdf3.saas.Constants;
import com.bstek.bdf3.saas.domain.Organization;
import com.bstek.bdf3.saas.service.DataSourceService;
import com.bstek.bdf3.saas.service.EntityManagerFactoryService;
import com.bstek.bdf3.security.orm.Url;

@Component
public class MasterDatabaseInitServiceImpl implements JpaUtilAble {

	@Autowired
	private EntityManagerFactoryService entityManagerFactoryService;

	@Autowired
	private DataSourceService dataSourceService;

	@Autowired
	private DataSourceProperties properties;

	private void runScripts(List<Resource> resources, DataSource dataSource) {
		ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
		populator.setContinueOnError(this.properties.isContinueOnError());
		populator.setSeparator(this.properties.getSeparator());
		if (this.properties.getSqlScriptEncoding() != null) {
			populator.setSqlScriptEncoding(this.properties.getSqlScriptEncoding().name());
		}
		for (Resource resource : resources) {
			populator.addScript(resource);
		}
		DatabasePopulatorUtils.execute(populator, dataSource);
	}

	@Override
	public void afterPropertiesSet(ApplicationContext arg0) {
//		EntityManager em = JpaUtil.createEntityManager(Url.class);
//		if (JpaUtil.linq(Url.class, em).count() == 0) {
			ClassPathResource resource = new ClassPathResource("master.sql");
			List<Resource> resources = new ArrayList<Resource>();
			resources.add(resource);

//			entityManagerFactoryService.getOrCreateEntityManagerFactory(master);
			Organization master = new Organization();
			master.setId(Constants.MASTER);
			DataSource ds = dataSourceService.getDataSource(master);
			this.runScripts(resources, ds);
//		}
	}
}
